<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    public static $USER_STATUS_INACTIVE = 1;
    public static $USER_STATUS_ACTIVE = 2;
    public static $USER_STATUS_BANNED = 3;

    public static $USER_STATUS_MAP = [
        ['key' => 1, 'text' => '未生效'],
        ['key' => 2, 'text' => '已生效'],
        ['key' => 3, 'text' => '已禁用'],
    ];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'nick_name', 'email', 'password', 'mobile',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public static function boot() {
        User::creating(function ($user) {
            if (!empty($user->password)) {
                $user->password = bcrypt($user->password);
            }
        });
        User::updating(function ($user) {
            if (!empty($user->password)) {
                $originUser = User::findOrFail($user->id);
                if ($originUser->password != $user->password) {
                    $user->password = bcrypt($user->password);
                }
            }
        });
    }

    public function userGroups()
    {
        return $this->belongsToMany('App\UserGroup', 'group_users', 'user_id', 'group_id')
            ->withPivot('is_primary_group');
    }

    public function roles()
    {
        return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
    }

    public function getSuperStatusText()
    {
        $suStatusMap = BaseDictionary::$YES_NO_MAP;
        foreach ($suStatusMap as $suStatus) {
            if ($suStatus['key'] === $this->is_super) {
                return $suStatus['text'];
            }
        }
        return null;
    }

    public function getStatusText()
    {
        $statusMap = self::$USER_STATUS_MAP;
        foreach ($statusMap as $status) {
            if ($status['key'] === $this->status) {
                return $status['text'];
            }
        }
        return null;
    }

    public function getDisplayName()
    {
        return empty($this->nick_name)?
            (empty($this->name)?
                (empty($this->email)?$this->mobile:$this->email)
                :$this->name)
            :$this->nick_name;
    }

    public function isSuper()
    {
        return $this->is_super === BaseDictionary::$KEY_YES;
    }

    public function isActive()
    {
        return $this->user_active === self::$USER_STATUS_ACTIVE;
    }

    public function hasLoginOnce()
    {
        return $this->has_login_once === BaseDictionary::$KEY_YES;
    }

    public function setHasLoginOnce()
    {
        $this->has_login_once = BaseDictionary::$KEY_YES;
        $this->save();
    }
}
